<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    title="选择配方"
    switchFullscreen
    @ok="submitForm"
    @cancel="close"
    style="top: 50px"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="formDisabled">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
<!--          <a-row>
            <a-col :span="6">
              <a-form-model-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item label="BOM版本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
                <a-input v-model="model.year"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item label="产品编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="model.code"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item label="产品规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noneSpec">
                <a-input v-model="model.noneSpec"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>-->

          <!-- 子表单区域 -->
          <a-row>
            <!-- 新增 -->
            <a-col :span="24">
<!--              <a-divider>已关联配方</a-divider>
              <a-row>
                <a-table
                  ref="table"
                  size="middle"
                  :scroll="{ x: true }"
                  bordered
                  :rowKey="(record) => record.id"
                  :columns="goodsFormulaTable.formulaColumn"
                  :dataSource="goodsFormulaTable.datasource"
                  :pagination="false"
                  :loading="goodsFormulaTable.loading"
                  :customRow="rowSelectChange"
                  class="j-table-force-nowrap1"
                >
                  <template slot="operation" slot-scope="text, record">
                    <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.id)">
                      <a href="javascript:;">删除</a>
                    </a-popconfirm>
                  </template>
                </a-table>
              </a-row>-->
<!--              <a-divider>配方清单</a-divider>-->
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="配方编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                    <a-input v-model="queryParam.formulaCode" placeholder="请输入配方编码"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="配方名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                    <a-input v-model="queryParam.formulaDefine" placeholder="请输入配方名称"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                <a-button @click="getFormulaDatasource" type="primary">查询</a-button>
                </a-col>
                  <a-col :span="2">
                <a-button @click="searchReset" type="primary">重置</a-button>
                  </a-col>
              </a-row>
              <a-row>
                <a-table
                  ref="table"
                  size="middle"
                  :scroll="{ x: true }"
                  bordered
                  rowKey="id"
                  :columns="formulaTable.formulaColumn"
                  :dataSource="formulaTable.datasource"
                  :pagination="formulaTable.ipagination"
                  :rowSelection="{ onChange: onSelectChange, selectedRow: onSelectRow, type: 'radio' }"
                  :loading="formulaTable.loading"
                  :customRow="rowSelectChange"
                  class="j-table-force-nowrap1"
                >
                </a-table>
              </a-row>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <!-- 表格 -->
              <a-table
                style="margin-left: 10px"
                ref="formulaDetailTable"
                bordered
                :data-source="formulaDetailTable.datasource"
                :columns="formulaDetailTable.formulaDetailColumn"
                :rowKey="(record) => record.id"
                :pagination="false"
              >
              </a-table>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
      <employee-list-modal ref="selectEmployee" @handlerOk="handleSelectEmployeeOk" />
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import { putAction } from '@api/manage'
import { postAction } from '@api/manage'
import { getAction } from '@api/manage'
import Big from 'big.js'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import EditableCell from '@comp/table/EditableCell'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'

export default {
  name: 'ErpGoodsFormularConModal',
  components: {
    ErpGoodsListModel,
    EditableCell,
    EmployeeListModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      title: '选择配方',
      modalWidth: 1250,
      category: '2',
      selectedFormular: {},
      queryParam: {
        formulaCode: '',
        formulaDefine: '',
      },
      model: {
        id: '',
        code: '',
        year: '',
        name: '',
        noneSpec: '',
      },
      goodsFormulaCon: {
        year: '',
        goodsId: '',
        formulaIds: [],
      },
      goodsFormulaTable: {
        loading: false,
        datasource: [],
        formulaColumn: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '配方年',
            dataIndex: 'formulaYear',
          },
          {
            title: 'BOM编码',
            dataIndex: 'code',
          },
          {
            title: 'BOM号',
            dataIndex: 'no',
          },

          {
            title: 'BOM名称',
            dataIndex: 'pattern',
          },
          {
            title: '类别',
            dataIndex: 'category_dictText',
          },
          {
            title: 'BOM类型',
            dataIndex: 'materialQuality',
          },
          {
            title: '制单人',
            dataIndex: 'createByName',
            width: 150,
          },
          {
            title: '制单日期',
            dataIndex: 'createTime',
          },
          {
            title: '类别',
            dataIndex: 'type_dictText',
          },
          {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            scopedSlots: { customRender: 'operation' },
          },
        ],
      },
      formulaTable: {
        loading: false,
        datasource: [],
        // 表头
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '30', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        formulaColumn: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '配方年',
            dataIndex: 'formulaYear',
          },
          {
            title: '配方编码',
            dataIndex: 'formulaCode',
          },
          {
            title: '配方号',
            dataIndex: 'formulaNumber',
          },

          {
            title: '配方名称',
            dataIndex: 'formulaDefine',
          },
          {
            title: '配方类别',
            dataIndex: 'formulaCategory_dictText',
          },
          {
            title: '配方类型',
            dataIndex: 'formulaType_dictText',
          },
/*          {
            title: '制单人',
            dataIndex: 'createByName',
            width: 150,
          },
          {
            title: '制单日期',
            dataIndex: 'createTime',
          },*/
          {
            title: '类别',
            dataIndex: 'formulaDesc_dictText',
          },
        ],
      },
      formulaDetailTable: {
        loading: false,
        datasource: [],
        // 表头
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '30', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        formulaDetailColumn: [
          {
            title: '物料编码',
            dataIndex: 'materialCode',
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
          },
          {
            title: '规格型号',
            dataIndex: 'materialSpec',
          },
          {
            title: '单位',
            dataIndex: 'materialUnit',
          },
          {
            title: '是否自带料',
            dataIndex: 'isSelfProvided_dictText',
          },
          {
            title: '配方%',
            dataIndex: 'formulaProportion',
          },
          {
            title: '实际数量',
            dataIndex: 'actualNumber',
          },
        ],
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      textareaLabelCol: {
        xs: { span: 12 },
        sm: { span: 2 },
      },
      textareaWrapperCol: {
        xs: { span: 40 },
        sm: { span: 21 },
      },
      confirmLoading: false,
      validatorRules: {
/*        code: [{ required: true, message: '请输入编号!' }],
        name: [{ required: true, message: '请输入名称!' }],
        year: [{ required: true, message: '请输入BOM版本号!' }],*/
      },
      url: {
        formulaList: '/ipstslformulalist/ipsTslFormulaList/list',
        formulaDetailList: '/ipstslformulalist/ipsTslFormulaList/queryIpsTslFormulaMaterialDetailByMainId',
        queryByGoodsId: '/base/erpGoodsFormula/queryByGoodsId',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    close() {
      this.visible = false;
    },
    rowSelectChange(record, index) {
      return {
        on: {
          click: (event) => {
            this.selectedFormular = record
            this.model.year = record.year
            this.getFormulaDetailList(record)
          },
        },
      }
    },
    getFormulaDetailList(record) {

      getAction(this.url.formulaDetailList, { id: record.id })
        .then((res) => {
          if (res.success) {
            let result = res.result
            this.formulaDetailTable.datasource = res.result
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    onSelectChange(record, selected, selectedRowKeys) {
      console.log('获取的数据', selected, this.selectedRowKeys, record)
      if (selected.length == 0) {
        this.formulaDetailTable.datasource = []
        return
      }
      // selected.forEach((item) => {
      //   params.push(item.id)
      // })
      let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
      selected.forEach((item) => {
        if (ids.indexOf(item.id) == -1) {
          ids.push(item.id)
          this.goodsFormulaTable.datasource.push(item)
        }
      })
      this.selectedFormular = selected[selected.length - 1]
      //this.goodsFormulaCon.formulaIds = ids
      this.getFormulaDetailList(selected[selected.length - 1])

      console.log("this.selectedFormular",this.selectedFormular)
    },
    //重置查询条件
    searchReset() {
      this.expandedRowKeys = []
      this.queryParam = {
        formulaCode: '',
        formulaDefine: '',
      }
      this.getFormulaDatasource()
    },

    onSelectRow(record, selected, selectedRows, nativeEvent) {
      let ids = []
      selected.forEach((item) => {
        ids.push(item.id)
      })
      this.goodsFormulaCon.formulaIds = ids
      if (selected) {
        let param = record.id
        getAction(this.url.formulaDetailList, { formulaCode: param })
          .then((res) => {
            if (res.success) {
              this.formulaDetailTable.datasource = res.result
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
        this.dataSourceBack.forEach((item) => {
          if (item.id == record.id) {
            this.formulaDetailTable.datasource.push(item)
          }
        })
      } else {
        // this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== record.id);
        this.checkSelectRows = this.checkSelectRows.filter((item) => item.id != record.id)
      }
    },
    getFormulaDatasource(goodsId) {
      console.log('-------------------')

      if (goodsId) {
        let queryFormulaParams = { goodsId: goodsId }
        //根据物料id查询是否已绑定配方
        getAction(this.url.queryByGoodsId, queryFormulaParams).then((res) => {
          if (res.success) {
            console.log('根据物料id查询是否已绑定BOM', res.result)
            this.goodsFormulaTable.datasource = res.result
            let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
            this.goodsFormulaCon.formulaIds = ids
          }
        })
      }

      let params = {}
      params.pageSize = this.formulaTable.ipagination.pageSize
      params.pageNo = this.formulaTable.ipagination.current
      params.formulaCode = this.queryParam.formulaCode
      params.formulaDefine = this.queryParam.formulaDefine
      getAction(this.url.formulaList, params).then((res) => {
        if (res.success) {
          console.log(res.result.records)
          this.formulaTable.datasource = res.result.records
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        // console.log(data);
        // console.log(data.employeeName);
        this.model.belongUser = data.employeeName
        this.$forceUpdate() //重新渲染UI
        // console.log(data.employeeName,this.model.owner);
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectEmployee.visible = true
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/wlbh'
      putAction(url, { name: '物料编号' }).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    //计算转换率
    safeDivision(numerator, denominator) {
      if (denominator === 0) {
        // 处理除数为0的情况，可以返回错误信息或默认值
        return 'Error: Division by zero'
      }
      console.log('计算')
      // 执行除法并保留两位小数
      return (numerator / denominator).toFixed(6)
    },

    noneSpecChange() {
      try {
        this.model.noneSpec = this.model.noneSpec.toUpperCase().trim()
        let tempSpec = this.model.noneSpec
        let k = tempSpec.indexOf('KG')
        let k1 = tempSpec.indexOf('G')
        if (k > 0) {
          let c = tempSpec.indexOf('*')
          let t1 = tempSpec.substr(0, k)
          let t2 = tempSpec.substr(c + 1)

          let bt1 = Number.parseInt(t1)
          let bt2 = Number.parseInt(t2)

          this.model.packSpec = bt1 * bt2 * 1000

          this.model.coRate = ((bt1 * bt2) / 1000).toFixed(6)
        } else if (k1 > 0) {
          let c = tempSpec.indexOf('*')
          let t1 = tempSpec.substr(0, k1)
          let t2 = tempSpec.substr(c + 1)
          let bt1 = new Big(t1)
          let bt2 = new Big(t2)
          let h = bt1.times(bt2)
          this.model.coRate = h.div(new Big(1000000))
        }
      } catch (e) {}
    },
    onWarehouseSelected(rows) {
      this.model.warehouseCode = rows.code
      this.model.warehouseName = rows.name
    },
    onGoodsCategorySelected(rows) {
      console.log(11111)

      this.model.categoryName = rows.name
      this.model.categoryNo = rows.code
      // 判断是否是成品，并且关联包材，如果是下方显示包材关联表
      let str = rows.name
      let productChar = '成品'
      let packageChar = '包材'
      let otherChar = '原料'
      let containsProductChar = str.includes(productChar)
      let containsPackageChar = str.includes(packageChar)
      let containsOtherChar = str.includes(otherChar)
      console.log('***********************')

      if (containsProductChar) {
        console.log('containsProductChar')
        this.productShow = true
        this.otherShow = false
        this.packageShow = false
      } else if (containsPackageChar) {
        console.log('containsPackageChar')
        this.productShow = false
        this.otherShow = false
        this.packageShow = true
      } else {
        console.log('containsOtherChar')

        this.productShow = false
        this.otherShow = true
        this.packageShow = false
      }
    },
    onChangeShowRow() {
      getAction('/goods/erpGoodsCategory/queryByCode', { code: this.model.categoryNo }).then((res) => {
        let str = res.result.name
        let char = '成品'
        let containsChar = str.includes(char)
        console.log(containsChar)
        console.log(this.model.isAssBc)
        if (containsChar && (this.model.isAssBc === 1 || this.model.isAssBc === '1')) {
          this.productShow = true
          console.log('1')
          console.log(this.productShow)
        } else {
          this.productShow = false
          console.log('2')
          console.log(this.productShow)
        }
      })
    },
    handleSwitchChange(newValue) {
      // newValue 是开关的新值
      console.log('开关的新值:', newValue)
      // 在这里调用你的方法或者进行其他操作
      if (newValue) {
        this.getSequenceNum()
      }
    },
    add(record) {
      // this.edit(this.modelDefault);
      console.log('addrecord')
      console.log(record)
      this.model.id = record[0].id
      this.model.code = record[0].code
      this.model.name = record[0].name
      this.model.noneSpec = record[0].noneSpec
      this.model.year = new Date().getFullYear()
      this.getFormulaDatasource(record[0].id)
      this.visible = true
    },
    edit(record) {
      this.model = Object.assign({}, record)
      console.log('--------model-----------')
      console.log(this.model)
      console.log(record)

      getAction('/base/erpGoods/queryErpGoodsPackageByMainId', { goodsId: this.model.id }).then((res) => {
        this.model.erpGoodsPackageList = res.result
      })
      this.onChangeShowRow()
    },
    submitForm() {
      const that = this
      this.goodsFormulaCon.goodsId = this.model.id
      this.goodsFormulaCon.year = this.model.year
      console.log('提交配方关联', this.goodsFormulaCon)
      // 触发表单验证
      that.$emit('formularOk', this.selectedFormular)
      this.visible = false
/*      postAction(this.url.add, this.goodsFormulaCon).then((res) => {
        if (res.success) {
          this.$message.success('关联成功')
          that.$emit('formularOk', this.selectedFormular)
          this.visible = false
        } else {
          this.$message.warning(res)
        }
      })*/
    },
    onDelete(key) {
      const datasource = [...this.goodsFormulaTable.datasource]
      this.goodsFormulaTable.datasource = datasource.filter((item) => item.id !== key)
      let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
      this.goodsFormulaCon.formulaIds = ids
    },
  },
}
</script>
